const fs = require("fs")
const path = require("path")
let Robot;
const Enums = {
    "name": "名称",
    "class": "班级",
    "money" : "点数",
    "pp": "体力",
    "ppMax": "体力上限",
    "actionState":"状态",
    "null": "无所事事",
}

const actionState = {
    "null" : {
        name:"无所事事",
    },
    "move" : {
        name:"移动",
        state: {
            hungry: -0.001,
            pp: -0.1
        }
    }
}

const skillP = {
    "f" : 40, 
    "e" : 80, 
    "d" : 120, 
    "c" : 160, 
    "b" : 180, 
    "a" : 200, 
    "s" : 255, 
}

const Areas = {
    "生活区": [
        {
            name:"食堂",
            data: {
                foods: {
                    "normal":{
                        name:"标准套餐",
                        point:250,
                        mockStateChange:{
                            hungry: 65,
                            mood: 10
                        }
                       
                    }
                }
            },
            funcs: [
                {
                    name:"购买"
                },
                {
                    name:"移动"
                }
            ]
        },
        {
            name:"宿舍",
            funcs: [
                {
                    name:"睡觉"
                },
                {
                    name:"移动"
                }
            ]
        },
        {
            name:"理发店",
            funcs: [
                {
                    name:"理发"
                },
                {
                    name:"移动"
                }
            ]
        }
    ]
}

const Skill = {
    "math": "e",
    "mathPoint": 0,
    "english": "e",
    "englishPoint": 0,
}

const storage = {
    base: {
        capacity: 0,
        capacityMax:50,
        equips: {
            cloth: {
                name:"校服",
                capacity: 3,
                weight: 0.3,
                storage: {
                    capacity: 0,
                    capacityMax:10,
                },
            },
            trousers: {
                capacity: 3,
                storage: {
                    capacity: 0,
                    capacityMax:10,
                },
                weight: 0.3,
                name:"校裤"
            },
        },
        items : [

        ]
    },
}

const mockState = {
    hungry: 50,
    maxHungry: 100,
    water: 100,
    MaxWater: 100,
    mood:50, // 心情 
}
const personArea = {
    area: "生活区",
    index: 1
}

let datas = {
    
}

let normalState = {
    hungry: -0.03,
    water: -0.045,
    pp: 0.1
}

getDatas()
saveDatas()
setInterval(() => {
    // 状态更新
    update()

    saveDatas()
}, 15000)

function update() {
    for (const user_id in datas) {
        let info = datas[user_id];

        // 体力系统
        if(info.pp < info.ppMax) {
            info.pp += info.state.pp;
            if(actionState[info.actionState] && actionState[info.actionState].state && actionState[info.actionState].state.pp) {
                info.pp += actionState[info.actionState].state.pp;
            }
        }

        // 饥饿系统
        if(info.mockState.hungry < info.mockState.maxHungry && info.mockState.hungry > 0) {
            info.mockState.hungry += info.state.hungry;
            if(actionState[info.actionState] && actionState[info.actionState].state && actionState[info.actionState].state.hungry) {
                info.hungry += actionState[info.actionState].state.hungry;
            }
        } else {
            if(info.mockState.hungry < 0){
                info.hungry = 0
            }
            if(info.mockState.hungry > info.mockState.maxHungry) {
                info.hungry = info.mockState.maxHungry
            }
        } 

        // 移动
        if(info.actionState == "move" && info.personArea.targetArea) {
            let {pp, area, index} = info.personArea.targetArea
            if(pp == 0) {
                info.personArea.area = area
                info.personArea.index = index
                info.actionState = "null"
                if(Robot) {
                    Robot.sendGroupMsg(info.personArea.targetArea.group_id, info.personArea.targetArea.message)
                }
                info.personArea.targetArea = {}
            } else {
                if(info.pp >= 1) {
                    info.personArea.targetArea.pp -= 1;
                    info.pp -= 1;
                }
            }
        } else {
            info.actionState = "null"
        }

    }
}

function saveDatas () {
    fs.writeFileSync(path.resolve(__dirname , "../../resource/datas.json"),JSON.stringify(datas))
}

function getDatas() {
    try {
        let str = fs.readFileSync(path.resolve(__dirname , "../../resource/datas.json")).toString()
        if(str) {
            datas = JSON.parse(str)
        } else {
            datas = {}
        }
    } catch (error) {
        datas = {}
    }
}



// 领取今日点数
function getTodayM(props) {
    let moneyGet = {
        a: 2000,
        b: 1600,
        c: 1300,
        d: 1000
    }
    let {user_id} = props;
    let msg = "";
    // 判断今日是否领取
    if(datas[user_id]) {
        if(datas[user_id].last_get && datas[user_id].last_get == nowDay()) {
            msg = "今日点数已领取"
        } else {
            datas[user_id].last_get = nowDay()
            datas[user_id].money += moneyGet[datas[user_id].class]
            msg = "已领取"+moneyGet[datas[user_id].class]+"点数 现在点数" + datas[user_id].money
        }
    } else {
        msg = "没有改用户数据"
    }
    //
    return msg
}

// 获取当前日期
function nowDay () {
    let time = new Date()
    return `${time.getFullYear()} ${time.getMonth()} ${time.getDate()}`
}

let fangdou = true

function bindQA(props) {
    let {data, group_ids,group_id, bot} = props
    let {message, user_id, sender} = data;
    if(group_ids.includes(group_id) && bot.gl.has(group_id)) {
        if(message[0].type=="text") {
            let text = message[0].data.text.trim()
            let date = new Date()
            let random = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
            let atText = `${random}[CQ:at,qq=${user_id},text=@${sender.nickname}]`
            let atUser = `[CQ:at,qq=${user_id},text=@${sender.nickname}]`
            if(/^sj +(.+)$/.test(text) && fangdou) {
                fangdou = false;
                let com = RegExp.$1;
                setTimeout(() => {
                    fangdou = true;
                    if(/^myinfo$/ig.test(com)) {  // 展示我的信息
                        if(datas[user_id]) {
                            data.reply(atText + showInfo(datas[user_id]) )
                        } else {
                            datas[user_id] = initUseDate({name:sender.nickname})
                            data.reply(atText + "初始化成功 " + showInfo(datas[user_id]) )
                        }
                    }
                    if(/^init$|^初始化$/ig.test(com)) {  // 初始化
                        if(datas[user_id]) {
                            data.reply(atText + "该用户数据已存在,无需初始化" )
                        } else {
                            datas[user_id] = initUseDate({name:sender.nickname})
                            data.reply(atText + "初始化成功")
                        }
                    }
                    if(/^打卡$/ig.test(com)) {  // 领取每日点数
                        if(!datas[user_id]) {
                            data.reply(atText + "无该用户数据 请输入sj init 初始化" )
                        } else {
                            data.reply(atText + getTodayM({user_id}))
                        }
                    }
                    
                    if(/^位置$|^area$/ig.test(com)) {  // 获取位置信息
                        if(!datas[user_id]) {
                            data.reply(atText + "无该用户数据 请输入sj init 初始化" )
                        } else {
                            data.reply(atText + getPersonArea({user_id}))
                        }
                    }
    
                    if(/^移动|^move|^move *to/ig.test(com)) {  // 移动命令
                        if(!datas[user_id]) {
                            data.reply(atText + "无该用户数据 请输入sj init 初始化" )
                        } else {
                            let actionMsg = actionOk(datas[user_id].actionState) 
                            if(actionMsg){
                                data.reply(atText + actionMsg )
                            } else {
                                if(/^(移动|move *to|move) *(.+)$/ig.test(com)){
                                    let param = RegExp.$2;
                                    data.reply(atText + moveTo({user_id,param,group_id,atText:atUser}))
                                } else {
                                    data.reply(atText + moveTo({user_id}))
                                }
                            }
                        }
                    }


                },200)
            }
        }
    }
}

// 状态判断是否可执行行为
function actionOk(actionState) {
    if(/^move$/.test(actionState)) {
       return "当前状态移动中, 不可执行命令" 
    }
}

function initUseDate(props){ // 初始化数据
    let {name} = props
    return {
        name,
        actionState:"null",
        pp: 50,
        ppMax: 100,
        state: JSON.parse(JSON.stringify(normalState)),
        class : "d",
        personArea: JSON.parse(JSON.stringify(personArea)),
        mockState: JSON.parse(JSON.stringify(mockState)),
        money: 1000
    }
}

function moveTo(props) { // 移动命令
    let {param,group_id,atText} = props
    let info = datas[props.user_id];  // 用户信息
    let {area, index} = info.personArea;  // 位置信息
    let areaArr = Areas[area]  // 地区建筑list
    let nowArea = areaArr[index]  // 当前建筑
    if(param) {
        // 1.寻找param  获取当前param
        let targetArea;
        let targetQu;
        let targetIndex;
        for (let qu in Areas) {
            let areaList = Areas[qu]
            areaList.forEach((v, i) => {
                if(v.name == param.trim()){
                    targetArea = v
                    targetQu = qu
                    targetIndex = i
                }
            })
        }
        if(targetIndex == index) {
            return "已在" + nowArea.name
        }
        if(targetArea) {
            // 2.计算体力消耗和时间消耗
            let pp;
            if(targetQu == area){
                pp = Math.ceil(Math.abs(targetIndex - index) / 3)
            } else {
                pp = Math.ceil(areaArr.length / 3) + getAreaLength(area, targetQu)
            }
            // 3.开始移动 状态更改 
            info.actionState = "move"
            info.personArea.targetArea = {
                area:targetQu,
                group_id, message:atText + "已到达"+targetArea.name,
                index:targetIndex,pp
            }
            return `正在前往${targetArea.name},预计需要${pp*15}~${pp*15 + 15}秒`
        } else {
            return "未知地点"
        }
    } else {
        // 解析当前地区
        let str = `你当前位于${area}的${nowArea.name}\n附近可去:${areaArr.map((v, i) => {
            return `${v.name}(pp:-${Math.ceil(Math.abs(i - index) / 3)})`
        }).filter((v, i) => i != index).join("\n")}` 
        // 解析其他地区
        return str
    }
}

function getAreaLength(area1, area2) {  // 跨区域体力消耗   
    return 1
}

function getPersonArea(props) { // 展示位置信息
    let info = datas[props.user_id];
    let personArea = info.personArea;
    let {area, index} = personArea;
    let areaArr = Areas[area]
    let nowArea = areaArr[index]
    let str = `你当前位于${area}的${nowArea.name}\n此地点命令有:${nowArea.funcs.map(v=>v.name).join(" ")}\n附近可去:${areaArr.map((v, i) => {
        return `${v.name}(pp:-${Math.ceil(Math.abs(i - index) / 3)})`
    }).filter((v, i) => i != index).join("\n")}` 

    return str
}

function showInfo(info) { // 展示个人信息
    let str = ""
    for (let key in info) {
        if (/^name$|^actionState$|^class$|^money$/ig.test(key)) {
            str += `${Enums[key]}:${info[key]} `
        }
    }
    let pp = ` 体力:${info.pp.toFixed(0)}/${info.ppMax}`
    return str + pp
}
















module.exports = function(props) {
    let {bot, data} = props;
    Robot = bot;
    let {group_id, message, user_id} = data;
    


    bindQA({
        group_ids: [747029011, 368074699, 657855092],
        group_id,
        bot,
        data,
    })




}
